package com.snail.controller;

import com.snail.config.ProjectUrlConfig;
import com.snail.entity.SellerInfo;
import com.snail.enums.ResultEnum;
import com.snail.exception.SellException;
import com.snail.service.SellerInfoService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;
import java.util.Map;

/**
 * @Author 【swg】.
 * @Date 2017/12/11 20:37
 * @DESC
 * @CONTACT 317758022@qq.com
 */
@Controller
@RequestMapping("/")
@Slf4j
public class SellerInfoController {

    @Autowired
    private SellerInfoService sellerInfoService;
    @Autowired
    private ProjectUrlConfig projectUrlConfig;

    @RequestMapping("/login")
    public String login(){
        return "/login/login";
    }

    @PostMapping("/login")
    public ModelAndView login(@RequestParam("username") String username,
                              @RequestParam("password") String password,
                              HttpSession session,
                              Map<String,Object> map) throws UnsupportedEncodingException, NoSuchAlgorithmException {
        //1、对输入的用户名和密码进行校验
        SellerInfo sellerInfo = new SellerInfo();
        try {
            sellerInfo = sellerInfoService.check(username,password);
            //2、登陆
            session.setAttribute("loginUser",sellerInfo);
            map.put("msg", ResultEnum.LOGIN_SUCC.getMessage());
            map.put("url","/sell/seller/order/list");
            return new ModelAndView("common/success");
        } catch (SellException e) {
            log.error("【校验失败】,username={},password={}",username,password);
            map.put("msg", ResultEnum.LOGIN_FAIL.getMessage());
            map.put("url","/sell/login");
            return new ModelAndView("common/error");
        }
    }

    @RequestMapping("/logout")
    public ModelAndView logout(HttpSession session,Map<String,Object> map){
        session.invalidate();
        map.put("msg", ResultEnum.LOGOUT_SUCCESS.getMessage());
        map.put("url","/sell/login");
        return new ModelAndView("/common/success");
    }
}
